'use strict';

const createConfig = require('uni-config-center');
const uidConfig = createConfig({
	pluginId: 'uni-id'
});

const uidObj = require('uni-id');
const {
	Controller
} = require('uni-cloud-router');

const dbcmd = uniCloud.database().command;

module.exports = class FxsController extends Controller {
	
	// 分销中心
	async data() {
		let response = {
			code: 1,
			msg: '',
			datas: {}
		};
		
		let uid = '';
		if (this.ctx.event.uniIdToken) {
			// 已登录，获取当前登录 uid
			const userRes = await uidObj.checkToken(this.ctx.event.uniIdToken);
			if (userRes.code == 0) {
				uid = userRes.uid;
			}
		}
		if (!uid) {
			response.msg = '当前未登录'
			return response;
		}
		
		const fxsRes = await this.db.collection('usemall-distributor').doc(uid).get();
		
		const configRes = await this.db.collection('usemall-distributor-parameter').get();
		const [config] = configRes.data;
		
		response.datas = fxsRes;
		response.datas.config = config;
		response.code = 0;
	
		return response;
	}
	
	// 提现明细
	async cashoutRecord() {
		let response = {
			code: 1,
			msg: '',
			datas: {}
		};
		
		const { state } = this.ctx.data;
		
		let uid = '';
		if (this.ctx.event.uniIdToken) {
			// 已登录，获取当前登录 uid
			const userRes = await uidObj.checkToken(this.ctx.event.uniIdToken);
			if (userRes.code == 0) {
				uid = userRes.uid;
			}
		}
		if (!uid) {
			response.msg = '当前未登录'
			return response;
		}
		
		let whereObj = {fxs_uid: uid};
		if (state) {
			whereObj.state = state;
		}
		
		const fxsRes = await this.db.collection('usemall-distributor-cashout').where(whereObj).orderBy("create_time", "desc").get();
		
		response.datas = fxsRes;
		response.code = 0;
	
		return response;
	}
	
	// 分销订单
	async order() {
		let response = {
			code: 1,
			msg: '',
			datas: {}
		};
		const start = Date.now();
		let uid = '';
		if (this.ctx.event.uniIdToken) {
			// 已登录，获取当前登录 uid
			const userRes = await uidObj.checkToken(this.ctx.event.uniIdToken);
			if (userRes.code == 0) {
				uid = userRes.uid;
			}
		}
		if (!uid) {
			response.msg = '当前未登录'
			return response;
		}
		
		const fxsRes = await this.db.collection('usemall-order').aggregate()
			.lookup({
				from: 'usemall-order-detail',
				localField: 'order_id',
				foreignField: 'order_id',
				as: 'order_details'
			})
			.match(
				dbcmd.and([
					{
						order_pay_state: '已付款'
					},
					dbcmd.or([
						{
							order_fxs_uid: uid
						},
						{
							order_fxs_uid2: uid
						}
					])
				])
			)
			.sort({"create_time": -1})
			.end();
		
		// console.log('fxsres', fxsRes);
		
		response.datas = [];
		fxsRes.data.forEach(x => {
			x.level = 0;
			if (x.order_fxs_uid == uid) {
				x.level = 1;
			}
			if (x.order_fxs_uid2 == uid) {
				x.level = 2;
				x.order_fxs_amount = x.order_fxs_amount2;
			}
			
			// 脱敏处理
			x.order_member_name = this.service.utils.desz(x.order_member_name);
			
			// 分销商品
			x.order_details = x.order_details.filter(x => x.is_fxs == '是');
			
			if (x.order_details && x.order_details.length && x.order_fxs_amount) {
				x.order_details.forEach(d => {
					if (x.order_fxs_uid2 == uid) {
						// 返回上上级佣金
						d.fxs_amount = d.fxs_amount2;
					}
				});
				
				response.datas.push(x);
			}
		});
	
		const end = Date.now();
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.duration = `耗时：${end - start}ms`;
		return response;
	}
	
	// 分销成员
	async member() {
		let response = {
			code: 1,
			msg: '',
			datas: {}
		};
		
		const start = Date.now();
		
		let uid = '';
		if (this.ctx.event.uniIdToken) {
			// 已登录，获取当前登录 uid
			const userRes = await uidObj.checkToken(this.ctx.event.uniIdToken);
			if (userRes.code == 0) {
				uid = userRes.uid;
			}
		}
		if (!uid) {
			response.msg = '当前未登录'
			return response;
		}
		
		const memberRes = await this.db.collection('usemall-member').field({
			member_session_key: false,
			member_password: false,
			member_access_token: false,
			member_openid: false
		}).where(
			dbcmd.or([
				{
					myfxs_uid: uid
				},
				{
					myfxs_uid2: uid
				}
			])
		).get();
		
		memberRes.data.forEach(x => {
			x.level = 0;
			if (x.myfxs_uid == uid) {
				x.level = 1;
			}
			if (x.myfxs_uid2 == uid) {
				x.level = 2;
				x.myfxs_profit_amount = x.myfxs_profit_amount2;
			}
			
			x.member_name = x.member_nickname;
			// 脱敏处理
			x.member_name = this.service.utils.desz(x.member_name);
		});
		
		response.datas = memberRes.data;
	
		const end = Date.now();
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.duration = `耗时：${end - start}ms`;
		return response;
	}
	
	// 待结佣金
	async record() {
		let response = {
			code: 1,
			msg: '',
			datas: {}
		};
		
		const { state } = this.ctx.data;
		
		let uid = '';
		if (this.ctx.event.uniIdToken) {
			// 已登录，获取当前登录 uid
			const userRes = await uidObj.checkToken(this.ctx.event.uniIdToken);
			if (userRes.code == 0) {
				uid = userRes.uid;
			}
		}
		if (!uid) {
			response.msg = '当前未登录'
			return response;
		}
		
		let whereObj = {fxs_uid: uid};
		if (state) {
			whereObj.state = state;
		}
		const fxsRes = await this.db.collection('usemall-distributor-record').where(whereObj).orderBy("create_time", "desc").get();
		
		response.datas = fxsRes;
		response.code = 0;
	
		return response;
	}
	
	// 申请提现
	async cashout() {
		let response = {
			code: 1,
		};
		
		let uid = '';
		let uname = '';
		
		if (this.ctx.event.uniIdToken) {
			// 已登录，获取当前登录 uid
			const userRes = await uidObj.checkToken(this.ctx.event.uniIdToken);
			if (userRes.code == 0) {
				uid = userRes.uid;
				uname = userRes.userInfo.nickname || userRes.userInfo.username;
			}
		}
		if (!uid) {
			response.msg = '当前未登录'
			return response;
		}
		
		// 申请提现金额（单位分）
		this.ctx.data.cashout_amount = parseInt(this.ctx.data.cashout_amount);
		
		const {
			cashout_amount,
			cashout_way,
			cashout_way_id
		} = this.ctx.data;
		
		if (cashout_amount <= 0) {
			this.throw('提现金额需大于0');
		}
		
		// 最低 0.3元
		// 最高 2000元
		const min_cashout = 0.3 * 100;
		const max_cashout = 2000 * 100;
		
		if (!(cashout_amount >= min_cashout && cashout_amount <= max_cashout)) {
			this.throw(`提现金额范围：${min_cashout / 100}~${max_cashout / 100}`);
		}
		
		const fxsRes = await this.db.collection('usemall-distributor').doc(uid).get();
		if (!(fxsRes && fxsRes.data.length === 1)) {
			response.msg = '无分销身份，请重新登录';
			return response;
		}
		let fxsData = fxsRes.data[0];
		
		if(cashout_amount > fxsData.fxs_cashout_amount) {
			this.throw('提现金额大于可提现金额' + fxsData.fxs_cashout_amount / 100 + '元');
		}
		
		const walletConfigRes = await this.db.collection('usemall-wallet-parameter').field({
				check_name: true,
				service_charge: true,
				pattern: true
			})
			.limit(1)
			.get();
		
		const [walletConfig] = walletConfigRes.data;
		if (walletConfig && walletConfig.check_name == 'FORCE_CHECK') {
			const userRes = await this.db.collection('usemall-member').doc(uid).field({
				member_truename: true
			}).get();
			if (!(userRes && userRes.data.length === 1)) {
				response.msg = '请重新登录';
				return response;
			}
			const [userData] = userRes.data;
			if (!userData.member_truename) {
				this.throw(`提现需填写真实姓名，请先完善个人信息`);
			}
		} 
		
		const cashoutRes = await this.db.collection('usemall-distributor-cashout').add({
			fxs_uid: uid, 
			fxs_cashout_amount: cashout_amount,
			fxs_cashout_way: cashout_way,
			fxs_cashout_way_id: cashout_way_id,
			state: '待审核',
			create_time: new Date().getTime(),
			create_uid: uid,
			create_uname: uname,
			version: 1,
			is_delete: 0,
			ip: this.ctx.context.CLIENTIP
		});
		
		try {
			// 消息通知
			// 不需要 await，只需发送请求即可
			const messageNotifyUrl = `${uidConfig.config('message-notify.url')}/301`;
			if (messageNotifyUrl.indexOf('http') === 0) {
				uniCloud.httpclient.request(messageNotifyUrl, {
					method: 'post',
					headers: {
						'message-notify-key': uidConfig.config('message-notify.key')
					},
					data: {
						id: cashoutRes.id,
						scene: 301,
						title: `申请分销提现`,
						uname: `${uname}`,
						money: `￥${(cashout_amount / 100).toFixed(2)}`,
						way: `${cashout_way}`
					},
					timeout: 30 * 1000,
					contentType: 'json',
					dataType: 'json'
				});
			}
		} catch(e) {
			console.log('message-notify err', e);
		}
		
		await this.db.collection('usemall-distributor').doc(uid).update({
			fxs_unprofit_amount: this.db.command.inc(cashout_amount),
			fxs_cashout_amount: this.db.command.inc(-cashout_amount),
			last_modify_time: new Date().getTime(),
			last_modify_uid: uid
		});
		
		await this.db.collection('usemall-distributor-log').add({
			fxs_uid: uid,
			oper_content: `申请提现[${(cashout_amount / 100).toFixed(2)}]元`,
			oper_type: '提现',
			oper_ip: this.ctx.context.CLIENTIP,
			remark: '',
			version: 1,
			is_delete: 0,
			create_time: new Date().getTime(),
			create_uid: uid
		});
		
		response.code = 0;
		response.msg = '提交成功';
		
		return response;
	}
	
}
